# ./.venv/Scripts/activate.ps1  切换虚拟目录

''' 创建数据库
python manage.py shell
from manage import db
db.create_all()
'''

''' migration and update
#python manage.py db init  初始化
#python manage.py db migrate -m "updateuser migration" 生产迁移文件
#python manage.py db upgrade 更新数据库
'''
#pip freeze >requirements.txt 生产requirements.txt 依赖库
#pip install -r requirements.txt 根据 requirements.txt 来安装对应的依赖包
import os
from app import create_app, db
from app.models import User, Role,Permission,Post
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from flask_admin import  Admin,BaseView,expose 
from flask_admin.contrib.sqla import ModelView #flask-admin 根据模型生产视图
from flask_babelex import Babel #国际化
from flask_admin.contrib.fileadmin import FileAdmin
import os.path as op
from wtforms import TextAreaField,TextAreaField
from wtforms.widgets import TextArea
app = create_app(os.getenv('FLASK_CONFIG') or 'default')

class CKTextAreaWidget(TextArea):
    def __call__(self, field, **kwargs):
        if kwargs.get('class'):
            kwargs['class'] += ' ckeditor'
        else:
            kwargs.setdefault('class', 'ckeditor')
        return super(CKTextAreaWidget, self).__call__(field, **kwargs)

class CKTextAreaField(TextAreaField):
    widget = CKTextAreaWidget()

class PostView(ModelView):
    extra_js = ['//cdn.ckeditor.com/4.6.0/standard/ckeditor.js'] #增加富文本编辑器

    form_overrides = {
        'body': CKTextAreaField
    }
    def __init__(self, session, **kwargs):
        super(PostView, self).__init__(Post, session, **kwargs)

#自定义User模型视图
class UserView(ModelView):
    column_searchable_list = ['username', 'email']
    column_labels ={
        'email':'邮箱',
        'username':'姓名',
        'confirmed':'是否确认',
        'location':'位置',
        'about_me':'关于我'
    }
    create_modal = True 
    edit_modal = True
    can_export = True
    export_types= ['xls']  #需要安装tablib库,可以解决中文乱码的问题
    column_editable_list = ['email', 'username']

    column_list = ('email', 'username','confirmed','location','about_me')
    def __init__(self, session, **kwargs):
        super(UserView, self).__init__(User, session, **kwargs)

admin = Admin(app, name='后台管理系统',template_mode='bootstrap3',base_template='/admin/mybase.html') #自定义模板
admin.add_view(UserView(db.session,name='用户管理'))
admin.add_view(PostView(db.session,name='文章管理'))

#使用flask_babelex汉化
babel = Babel(app)
app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'

#文件管理
path=op.join(op.dirname(__file__),"app/static")
admin.add_view(FileAdmin(path,'/app/static',name="静态文件管理"))

manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role,Permission=Permission,Post=Post)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    app.debug = False
    #manager.run()
    app.run(host='localhost', port=5000)